package app.itgungnir.compose.wan.business.message

import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MarkChatRead
import androidx.compose.material.icons.filled.MarkChatUnread
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import app.itgungnir.compose.wan.widgets.TabItem
import app.itgungnir.compose.wan.widgets.WanPagingList
import app.itgungnir.compose.wan.widgets.WanScaffold
import app.itgungnir.compose.wan.widgets.WanTabLayout
import com.google.accompanist.insets.navigationBarsPadding

@Composable
fun MessageScreen(navController: NavController = rememberNavController()) {
    val viewModel = viewModel<MessageViewModel>()
    // UI
    WanScaffold(
        modifier = Modifier.navigationBarsPadding(),
        title = "站内消息",
        navController = navController
    ) {
        val tabs = listOf(
            TabItem(
                icon = Icons.Filled.MarkChatUnread,
                title = "未读消息",
                screen = { MessageTabItemScreen(true, viewModel = viewModel) }
            ),
            TabItem(
                icon = Icons.Filled.MarkChatRead,
                title = "已读消息",
                screen = { MessageTabItemScreen(false, viewModel = viewModel) }
            )
        )
        WanTabLayout(modifier = Modifier.padding(it), tabs = tabs)
    }
    // State observation
    UnreadMessageReadStateObservation(viewModel = viewModel, navController = navController)
}

@Composable
private fun MessageTabItemScreen(unread: Boolean, viewModel: MessageViewModel = viewModel()) {
    val pagingItems = when (unread) {
        true -> viewModel.unreadDataFlow.collectAsLazyPagingItems()
        else -> viewModel.readDataFlow.collectAsLazyPagingItems()
    }
    WanPagingList(pagingItems = pagingItems) {
        items(pagingItems) {
            MessageItem(item = it)
        }
    }
}

@Composable
private fun UnreadMessageReadStateObservation(
    viewModel: MessageViewModel = viewModel(),
    navController: NavController = rememberNavController()
) {
    val unreadMessageReadState by viewModel.unreadMessageReadState.collectAsState()
    LaunchedEffect(key1 = unreadMessageReadState) {
        if (unreadMessageReadState) {
            navController.previousBackStackEntry?.savedStateHandle?.set("user_read_message", true)
        }
    }
}
